﻿using CodeProject;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace DirToCSV
{
    class Program
    {
        static int Main(string[] args)
        {
            if (Testa_Argumentos(args) > 0)
            {
                return 1;
            }

            // String Caminho
            string Caminho = "";
            if (args[0].Trim() == "")
            {
                Caminho = ".";
            }
            else
            {
                Caminho = args[0].Trim();
            }
            
            int count_feedback = 100;
            String Arquivo_Saida = "DirToCSV.csv";

            int m;
            bool f;

            if (args.Length > 1)
            {
                f = int.TryParse(args[1], out m);
                if (!f)
                {
                    // String Caminho

                    if (args[1].Trim() == "")
                    {
                        Arquivo_Saida = "DirToCSV.csv";
                    }
                    else
                    {
                        Arquivo_Saida = args[1].Trim();
                    }
                }
                else
                {
                    count_feedback = m;
                }
            }
                       
            if (args.Length > 2) { 
                f = int.TryParse(args[2], out m);
                if (!f)
                {
                    return 2;
                } else {
                    count_feedback = m;
                }
            }

            // Varre o diretório e grava no arquivo CSV
            System.Console.WriteLine("==============================================================================");
            System.Console.WriteLine("DirToCSV Utility");
            System.Console.WriteLine("==============================================================================");
            System.Console.WriteLine("");
            System.Console.WriteLine("Scan in: " + Caminho);
            System.Console.WriteLine("Write in: " + Arquivo_Saida);
            System.Console.WriteLine("");
            GetDirectorySize(Caminho, Arquivo_Saida, count_feedback);
            System.Console.WriteLine("");
            System.Console.WriteLine("Arquivo '" + Arquivo_Saida + "' gerado com sucesso, finalizando.");
            System.Console.WriteLine("");
            return 0;
        }

        static int Testa_Argumentos(string[] args)
        {
            // Test if input arguments were supplied: 
            if (args.Length < 1 || args.Length > 3)
            {
                Usage();
                return 1;
            }
            if (args.Length > 1) { 
                int m;
                bool f = int.TryParse( args[1], out m);
                if (!f)
                {
                    if (args.Length > 2)
                    {
                        f = int.TryParse(args[2], out m);
                        if (!f)
                        {
                            Usage();
                            return 1;
                        }
                    }
                }
            }
            return 0;
        }

        static void Usage()
        {
            System.Console.WriteLine("==============================================================================");
            System.Console.WriteLine("DirToCSV Utility");
            System.Console.WriteLine("==============================================================================");
            System.Console.WriteLine("");
            System.Console.WriteLine("Usage: DirToCSV <path> [<CSV File Name>] [<Lines Response Feedback>]");
            System.Console.WriteLine("");
        }

        static string GetDirectorySize(string parentDir, string file, int count_feedback)
        {
            long totalFileSize = 0;
            TextWriter R;
            FileData[] dirFiles = { };
            char[] l = {'\\'};
            parentDir = parentDir.TrimEnd(l) + "\\";

            try
            {
                R = File.CreateText(file);
            }
            catch (Exception E)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("Erro ao abrir o arquivo '" + file + "' : " + E.Message);
                System.Console.WriteLine("Encerrando!!");
                System.Console.WriteLine("");
                return "";
            }

            try
            {
                dirFiles = FastDirectoryEnumerator.GetFiles(parentDir, "*.*", SearchOption.AllDirectories);
            }
            catch (Exception E)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("Erro ao efetuar o scan em '" + parentDir + "' : " + E.Message);
                System.Console.WriteLine("Encerrando!!");
                System.Console.WriteLine("");
                return "";
            }

            
                
                // do something with your file array
            //}
            //catch (UnauthorizedAccessException E)
            //{
            //    Console.WriteLine("\nErro: " + E.Message);
            //}
            
            //string fileName = "";
            parentDir = parentDir.TrimEnd(l);
            Console.WriteLine("\n\n");
            R.WriteLine("\"Caminho_Completo\";\"Nivel 0\";\"Nivel 1\";\"Nivel 2\";\"Nivel 3\";\"Nivel 4\";\"Nivel 5\";\"Nivel 6\";\"Nivel 7\";\"Pasta\";\"Nome\";\"Extensao\";\"Tamanho_Bytes\"");
            long ct = 0;
            string pasta_nivel1 = "";
            string pasta_nivel2 = "";
            string pasta_nivel3 = "";
            string pasta_nivel4 = "";
            string pasta_nivel5 = "";
            string pasta_nivel6 = "";
            string pasta_nivel7 = "";
            string w = "";

            foreach (FileData file_item in dirFiles)
            {
                // Use FileInfo to get length of each file.
               try
               {
                    ct++;
                    if (ct % count_feedback == 0) { Console.Write("File count:" + ct.ToString() + "\r"); };
                    //FileInfo info = new FileInfo(file_item);
                    totalFileSize = totalFileSize + file_item.Size; //+ info.Length;

                    pasta_nivel1 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 1);
                    pasta_nivel2 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 2);
                    pasta_nivel3 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 3);
                    pasta_nivel4 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 4);
                    pasta_nivel5 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 5);
                    pasta_nivel6 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 6);
                    pasta_nivel7 = GetDiretorioNivel(parentDir, file_item.Path.TrimEnd(l), 7);
                    
                    w = "\"" + file_item.FullName + "\";\"" + parentDir + "\";\"" + pasta_nivel1 + "\";\"" + pasta_nivel2 + "\";\"" + pasta_nivel3 + "\";\"" + pasta_nivel4 + "\";\"" + pasta_nivel5 + "\";\"" + pasta_nivel6 + "\";\"" + pasta_nivel7 + "\";\"" + file_item.Path + "\";\"" + file_item.Name + "\";\"" + file_item.Extension.TrimStart('.') + "\";" + file_item.Size.ToString();
                    w = Encoding.UTF8.GetString(Encoding.Default.GetBytes(w));
                    R.WriteLine(w);
                }
                catch (Exception E)
                {
                    Console.WriteLine("\nErro: " + E.Message);
                }
            }
            return String.Format("{0:fs}", totalFileSize);

            R.Close();
        }

        static string GetDiretorioNivel(string DirPath, string Path, int nivel)
        {
            string temp = "";
            int contador_Path_DirPath = 0;

            DirPath = DirPath.TrimEnd('\\') + "\\";
            Path = Path.TrimEnd('\\') + "\\";

            if (DirPath == Path ) //&& nivel == 0)
            {
                return DirPath;
            }

            temp = Path;
            do
            {
                if (Directory.GetParent(temp) != null)
                {
                    contador_Path_DirPath++;
                    temp = Directory.GetParent(temp).FullName;
                }
                else
                {

                }
            }
            while (temp.Length > DirPath.Length);

            contador_Path_DirPath -= nivel;
            temp = Path;
            for (var i = 1; i <= contador_Path_DirPath; i++){
                temp = Directory.GetParent(temp).FullName;
            }
            return temp;
        }
    }

}
